<template>
  <div
    class="login"
    v-if="token == '' || token == undefined || token.length == 0"
  >
    <div class="sportContent">
      <div class="left">
        <div class="zi1">祥芸来管理平台</div>
        <div class="zi2">SHOPPING MANAGEMENT PLATFORM</div>
        <div class="line"></div>
      </div>
      <div class="right">
        <h3 class="loginTitle">欢&nbsp;迎&nbsp;登&nbsp;录</h3>
        <el-tabs v-model="activeName" @tab-click="activeTabs">
<!--          <el-tab-pane label="手机号码登录" name="1">-->
<!--            <el-form-->
<!--              ref="loginFormPhone"-->
<!--              :model="loginFormPhone"-->
<!--              :rules="loginRulesPhone"-->
<!--              class="login-form"-->
<!--            >-->
<!--              <el-form-item prop="phoneNumer">-->
<!--                <el-input-->
<!--                  v-model="loginFormPhone.phoneNumer"-->
<!--                  type="text"-->
<!--                  autocomplete="off"-->
<!--                  placeholder="手机号"-->
<!--                  maxlength="11"-->
<!--                >-->
<!--                  <i class="el-icon-phone" slot="prefix"></i>-->
<!--                </el-input>-->
<!--              </el-form-item>-->
<!--              <el-form-item prop="verifyCode">-->
<!--                <div class="flex_item">-->
<!--                  <el-input-->
<!--                    v-model="loginFormPhone.verifyCode"-->
<!--                    type="text"-->
<!--                    autocomplete="off"-->
<!--                    placeholder="验证码"-->
<!--                    style="margin-right: 10px"-->
<!--                    maxlength="4"-->
<!--                    @keyup.enter.native="handleLogin('loginFormPhone')"-->
<!--                  >-->
<!--                    <svg-icon-->
<!--                      slot="prefix"-->
<!--                      icon-class="password"-->
<!--                      class="el-input__icon input-icon"-->
<!--                    />-->
<!--                  </el-input>-->
<!--                  <el-button-->
<!--                    type="primary"-->
<!--                    @click="getVerifyCode"-->
<!--                    :disabled="msgKey"-->
<!--                    >{{ msgText }}-->
<!--                  </el-button>-->
<!--                </div>-->
<!--              </el-form-item>-->
<!--              <el-form-item style="width: 100%">-->
<!--                <el-button-->
<!--                  :loading="loading"-->
<!--                  size="medium"-->
<!--                  type="primary"-->
<!--                  style="width: 100%"-->
<!--                  @click.native.prevent="handleLogin('loginFormPhone')"-->
<!--                >-->
<!--                  <span v-if="!loading">登 录</span>-->
<!--                  <span v-else>登 录 中...</span>-->
<!--                </el-button>-->
<!--              </el-form-item>-->
<!--            </el-form>-->
<!--          </el-tab-pane>-->
          <el-tab-pane label="密码登录" name="1">
            <el-form
              ref="loginForm"
              :model="loginForm"
              :rules="loginRules"
              class="login-form"
            >
              <el-form-item prop="username">
                <el-input
                  v-model="loginForm.username"
                  type="text"
                  auto-complete="off"
                  placeholder="账号"
                  @keyup.enter.native="handleLogin('loginForm')"
                >
                  <svg-icon
                    slot="prefix"
                    icon-class="user"
                    class="el-input__icon input-icon"
                  />
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  auto-complete="off"
                  placeholder="密码"
                  @keyup.enter.native="handleLogin('loginForm')"
                  show-password
                >
                  <svg-icon
                    slot="prefix"
                    icon-class="password"
                    class="el-input__icon input-icon"
                  />
                </el-input>
              </el-form-item>

              <el-form-item prop="code">
                <el-input
                  v-model="loginForm.code"
                  placeholder="验证码"
                  style="width: 63%"
                  @keyup.enter.native="handleLogin('loginForm')"
                >
                  <svg-icon
                    slot="prefix"
                    icon-class="validCode"
                    class="el-input__icon input-icon"
                  />
                </el-input>
                <div class="login-code">
                  <img :src="codeUrl" @click="getCode" />
                </div>
              </el-form-item>
              <el-checkbox
                v-model="loginForm.rememberMe"
                style="margin: 0px 0px 25px 0px"
                v-if="activeName == '2'"
                >记住密码</el-checkbox
              >
              <el-form-item style="width: 100%">
                <el-button
                  :loading="loading"
                  size="medium"
                  type="primary"
                  style="width: 100%"
                  @click.native.prevent="handleLogin('loginForm')"
                >
                  <span v-if="!loading">登 录</span>
                  <span v-else>登 录 中...</span>
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  底部  -->
    <!-- <div class="el-login-footer">
      <span>技术支持:北京华信瑞德信息技术有限公司</span>
    </div> -->
  </div>
  <div v-else>登陆中。。</div>
</template>

<script>
import {
  getCodeImg,
  bsSsoLogin,
  getQueryString,
  applogin,
  getVerifyCode,
} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";

const MSGINIT = "发送验证码",
  MSGERROR = "验证码发送失败",
  MSGSCUCCESS = "${time}秒后重发",
  MSGTIME = 120;

import { isvalidatemobile } from "@/utils/validate";

export default {
  name: "Login",
  data() {
    const validatePhone = (rule, value, callback) => {
      if (isvalidatemobile(value)[0]) {
        callback(new Error(isvalidatemobile(value)[1]));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value.length != 4) {
        callback(new Error("请输入4位数的验证码"));
      } else {
        callback();
      }
    };
    return {
      token: "",
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        phoneNumer: "",
        verifyCode: "",
      },
      loginRules1: {
        phoneNumer: [
          {
            required: true,
            trigger: "change",
            validator: validatePhone,
          },
        ],
        verifyCode: [
          {
            required: true,
            trigger: "change",
            validator: validateCode,
          },
        ],
        // username: [{
        //     required: true,
        //     trigger: "blur",
        //     message: "用户名不能为空"
        // }, ],
        // password: [{
        //     required: true,
        //     trigger: "blur",
        //     message: "密码不能为空"
        // }, ],
        // code: [{
        //     required: true,
        //     trigger: "blur",
        //     message: "验证码不能为空"
        // }, ]
      },
      loginRules: {
        username: [
          {
            required: true,
            trigger: "change",
            message: "用户名不能为空",
          },
        ],
        password: [
          {
            required: true,
            trigger: "change",
            message: "密码不能为空",
          },
        ],
        code: [
          {
            required: true,
            trigger: "change",
            message: "验证码不能为空",
          },
        ],
      },

      loading: false,
      redirect: undefined,
      activeName: "1",
      msgKey: false,
      msgText: MSGINIT,
      msgTime: MSGTIME,
      loginFormPhone: {
        phoneNumer: "",
        verifyCode: "",
      },
      loginRulesPhone: {
        phoneNumer: [
          {
            required: true,
            trigger: "change",
            validator: validatePhone,
          },
        ],
        verifyCode: [
          {
            required: true,
            trigger: "change",
            validator: validateCode,
          },
        ],
      },
    };
  },
  // computed: {
  //     loginRules() {
  //         if (this.activeName == '1') {
  //             return this.loginRules1
  //         } else {
  //             return this.loginRules2
  //         }
  //     }
  // },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    // let query=this.$route.query;
    let token = getQueryString("token");
    this.token = token;
    this.getCode();
    this.getCookie();
  },
  methods: {
    reset() {
      let uuid = this.loginForm.uuid;
      let rememberMe = this.loginForm.rememberMe;
      this.loginForm = {
        username: "",
        password: "",
        code: "",
        uuid,
        rememberMe,
        phoneNumer: "",
        verifyCode: "",
      };
      this.loginFormPhone = {
        phoneNumer: "",
        verifyCode: "",
      };
      this.resetForm("loginForm");
      this.resetForm("loginFormPhone");
    },
    activeTabs() {
      this.reset();
    },
    //获取验证码
    getCode() {
      getCodeImg().then((res) => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
        if (res.capStr == undefined) {
          if (
            this.token != undefined &&
            this.token != "" &&
            this.token.length > 0
          ) {
            this.loginForm.code = res.capStr;
            console.info(this.loginForm);
            bsSsoLogin(this.token).then((resSso) => {
              console.info(resSso);
              if (resSso.code == 500) {
                alert("登录有误");
                return;
              }
              this.loginForm.username = resSso.userName;
              this.loginForm.password = resSso.userName + "_hxrd";
              this.handleSsoLogin();
            });
          }
        } else {
          if (
            this.token != undefined &&
            this.token != "" &&
            this.token.length > 0
          ) {
            this.loginForm.code = res.capStr;
            bsSsoLogin(this.token).then((resSso) => {
              if (resSso.code == 500) {
                alert("登录有误");
                return;
              }
              this.loginForm.username = resSso.userName;
              this.loginForm.password = resSso.userName + "_hxrd";
              this.handleSsoLogin();
            });
          }
          // });
        }
      });
    },
    //单点登录
    handleSsoLogin() {
      this.loading = true;
      Cookies.remove("username");
      Cookies.remove("password");
      Cookies.remove("rememberMe");
      this.loginForm.username = this.loginForm.phoneNumer;
      this.loginForm.code = this.loginForm.verifyCode;
      this.$store
        .dispatch("Login", this.loginForm)
        .then((res) => {
          let code = res.code;
          if (code == 200) {
            this.$router.push({
              path: this.redirect || "/",
            });
          } else {
            // this.msgError('网络出现问题，请稍等~~');
            this.msgError(res.msg);
            setTimeout(() => {
              this.loading = false;
              this.$router.replace({
                path: this.redirect || "/",
              });
            }, 1000);
          }
        })
        .catch(() => {
          this.loading = false;
          this.getCode();
        });
    },
    //获取cookie的值
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    //点击登录
    handleLogin(refName) {
      this.$refs[refName].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.activeName == "2") {
            this.loginFormPhone.username = this.loginFormPhone.phoneNumer;
            this.loginFormPhone.code = this.loginFormPhone.verifyCode;

            this.$store
              .dispatch("LoginPhone", this.loginFormPhone)
              .then((res) => {
                let code = res.code;
                if (code == 200) {
                  this.$router.push({
                    path: this.redirect || "/",
                  });
                } else {
                  // this.msgError('网络出现问题，请稍等~~');
                  this.getCode();
                  this.msgError(res.msg);
                  setTimeout(() => {
                    this.loading = false;
                    this.$router.replace({
                      path: this.redirect || "/",
                    });
                  }, 1000);
                }
              })
              .catch(() => {
                this.loading = false;
                this.getCode();
              });
          } else {
            if (this.loginForm.rememberMe) {
              Cookies.set("username", this.loginForm.username, {
                expires: 30,
              });
              Cookies.set("password", encrypt(this.loginForm.password), {
                expires: 30,
              });
              Cookies.set("rememberMe", this.loginForm.rememberMe, {
                expires: 30,
              });
            } else {
              Cookies.remove("username");
              Cookies.remove("password");
              Cookies.remove("rememberMe");
            }

            this.$store
              .dispatch("Login", this.loginForm)
              .then((res) => {
                let code = res.code;
                if (code == 200) {
                  this.$router.push({
                    path: this.redirect || "/",
                  });
                } else {
                  // this.msgError('网络出现问题，请稍等~~');
                  this.getCode();
                  this.msgError(res.msg);
                  setTimeout(() => {
                    this.loading = false;
                    this.$router.replace({
                      path: this.redirect || "/",
                    });
                  }, 1000);
                }
              })
              .catch(() => {
                this.loading = false;
                this.getCode();
              });
          }
        }
      });
    },
    AppLogin() {
      applogin({
        username: "admin",
        password: "admin123",
      }).then((res) => {
        console.log("登录成功");
      });
    },
    // 获取验证码
    getVerifyCode() {
      if (this.msgKey) return;
      if (!this.loginFormPhone.phoneNumer) {
        this.$message.error("请输入手机号码");
      } else if (!/^1[3456789]\d{9}$/.test(this.loginFormPhone.phoneNumer)) {
        this.$message.error("手机号格式不正确");
      } else {
        getVerifyCode(this.loginFormPhone.phoneNumer).then((res) => {
          // timer()
          this.$message.success("验证码发送成功");
          this.msgText = MSGSCUCCESS.replace("${time}", this.msgTime);
          this.msgKey = true;
          const time = setInterval(() => {
            this.msgTime--;
            this.msgText = MSGSCUCCESS.replace("${time}", this.msgTime);
            if (this.msgTime == 0) {
              this.msgTime = MSGTIME;
              this.msgText = MSGINIT;
              this.msgKey = false;
              clearInterval(time);
            }
          }, 1000);
        });
      }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  /*background-image: url("../assets/image/login-background.jpg");*/
  background-image: url("../assets/image/bg.png");
  background-size: cover;
}

.sportContent {
  width: 100%;
  padding: 0 241px;
  height: 50%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  // position: relative;
}

.sportContent .left {
  // margin-top: -180px;
  // position: absolute;
  // left: 10%;
  // bottom: 100px;
  margin-right: 200px;
  font-size: 38px;
  color: #fff;
  font-family: SourceHanSansSC-Heavy;
  // font-weight: bold;
  // text-align: center;

  .zi1 {
    font-size: 48px;
    color: rgba(255, 255, 255, 0.85);
    text-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.16);
    letter-spacing: 15px;
  }

  .zi2 {
    font-size: 18px;
    color: rgba(255, 255, 255, 0.85);
    text-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.16);
    margin-top: 10px;
    letter-spacing: 2px;
  }

  .line {
    width: 150px;
    height: 5px;
    background: #fff;
    margin-top: 20px;
  }

  .left_img {
    width: 25vw;
    margin-top: 20px;

    img {
      width: 100%;
    }
  }
}

.sportContent .right {
  position: absolute;
  right: 200px;
  background: #ffffff;
  border-radius: 20px;
  padding: 25px 25px 5px 25px;
}

.loginTitle {
  margin: 0px auto 16px auto;
  text-align: center;
  color: #1a1a1a;
  font-weight: 600;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  background: transparent;
  background-color: rgba(255, 255, 255, 1);
  border-radius: 14px;
  width: 350px;
  // padding: 25px 25px 5px 25px;
  // margin-left: 30px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    width: 100%;
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.flex_item {
  display: flex;
  align-items: center;
}
</style>
